<?php
class CI_Option
{
    var $ci;
    var $config;

    function __construct()
    {
        $this->ci = & get_instance();
        $this->ci->load->model('option_model');
    }
    
    function editOptions($params)
    {
        if(!empty($params))
        {
            $this->ci->load->library('Form_validation');
            $val = $this->ci->form_validation;
            
            foreach ($params as $key=>$value)
            {
                $val->set_rules($key, $value['lang'], $value['validation']);
            }
            foreach ($_POST as $key=>$item)
            {
                if(is_array($item))
                {
                    $_POST[$key] = serialize($item);
                }
            }
            
            if ($val->run() == FALSE)
            {
                $data['options'] = $params;
                
                lv('lib/option/edit_view',$data);
            }
            else
            {
                //如果checkbox不选，post给的值为空，所以循环config而不是post
                foreach ($params as $key =>$value)
                {
                    $postValue = $this->ci->input->post($key);
                    if($postValue === FALSE)
                    {
                        $postValue="";
                    }
                    $this->ci->option_model->editOption($key,$postValue);
                }
                redirect($this->ci->uri->uri_string(),'refresh');
            }	
        }
    }
    
    function getOption($key)
    {
        $query = gc("option_model", "getOption",array('key'=>$key));
        
        if($query->num_rows()>0)
        {
            $arr = $query->row_array();
            return $arr['value'];
        }
        return NULL;
    }
    
    function getOptions()
    {
    	$query = gc("option_model", "getOptions");
    	$res = array();
    	
        if($query->num_rows()>0)
        {
            foreach($query->result_array() as $item)
            {
            	$key = $item['key'];
            	$val = $item['value'];
            	$res[$key] = $val;
            }
        }
        return $res;
    }
}